package com.thermal.thermal_inspection.controller;

import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.Report;
import com.thermal.thermal_inspection.service.AccountService;
import com.thermal.thermal_inspection.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportService reportService;
    @Autowired
    AccountService accountService;
    private static final String UPLOAD_DIR = "reports/";

    @GetMapping("/{id}")
    public CommonResponse<Report> get(@PathVariable Integer id) {
        return CommonResponse.createForSuccess(reportService.getById(id));
    }

    @GetMapping("/list")
    public CommonResponse<List<Report>> list() {
        System.out.println("进入获取list");
        return CommonResponse.createForSuccess(reportService.getAll());
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("userId") int userId) {
        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 获取原始文件名、构建新文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return ResponseEntity.badRequest().body("无效的文件名");
            }

            int dotIndex = originalFilename.lastIndexOf(".");
            String baseName = (dotIndex != -1) ? originalFilename.substring(0, dotIndex) : originalFilename;
            String extension = (dotIndex != -1) ? originalFilename.substring(dotIndex) : "";

            String timestamp = String.valueOf(System.currentTimeMillis());
            String newFilename = baseName + "_user" + userId + "_" + timestamp + extension;

            // 保存到数据库
            Report report = new Report();
            report.setPatientId(userId);
            report.setReportName(newFilename); // 设置报告名称（如：文件名）
            report.setCheckName("无"); // 根据业务可修改或从前端传入
            report.setCheckTime(new Timestamp(System.currentTimeMillis())); // 当前时间作为检查时间
            report.setCheckType("无"); // 可设置为具体类型，如“视力检测”等
            report.setFileUrl(""); // 假设你文件上传后存放的路径为 /uploads/
            report.setPatientName(accountService.getUserInfo(userId).getRealName());

            reportService.add(report); // 使用当前的 service 方法


            // 保存文件
            Path filePath = uploadPath.resolve(newFilename);
            file.transferTo(filePath);

            return ResponseEntity.ok("文件上传成功: " + newFilename);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }

    @PutMapping("/update")
    public CommonResponse<Integer> update(@RequestBody Report report) {
        return CommonResponse.createForSuccess(reportService.update(report));
    }

    @DeleteMapping("/delete/{id}")
    public CommonResponse<Integer> delete(@PathVariable Integer id) {
        return CommonResponse.createForSuccess(reportService.delete(id));
    }
    // ReportController.java

    @GetMapping("/search")
    public CommonResponse<List<Report>> searchReports(
            @RequestParam String patientName,
            @RequestParam String gender,
            @RequestParam String phone) {
        System.out.println("patientName"+patientName);
        System.out.println("gender"+gender);
        System.out.println("phone"+phone);
        List<Report> list = reportService.searchReports(patientName, gender, phone);
        System.out.println(list);
        return CommonResponse.createForSuccess(list);
    }
    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");

            Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename*=UTF-8''" + encodedFilename)
                        .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream; charset=UTF-8")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}

